package com.eurekaserver.common.listener;

import com.eurekaserver.common.util.DingDingMessageUtil;
import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**Eureka事件监听
 * @author ：zhangqiang
 * @create ：2018-09-14 14:32
 **/
@Component
public class EurekaChangeListener {

	@Value("${eureka-server.active}")
	private String eurekaServerActive;

	private static final Logger logger = LoggerFactory.getLogger(EurekaChangeListener.class);
//	EurekaInstanceCanceledEvent:服务下线事件
//	EurekaInstanceRegisteredEvent:服务注册事件
//	EurekaInstanceRenewedEvent:服务续约事件
//	EurekaRegistryAvailableEvent:Eureka注册中心启动事件
//	EurekaServerStartedEvent:Eureka Server启动事件

	@EventListener
	public void listen(EurekaInstanceCanceledEvent event) {
		//某个服务下线，需要通知到！
		if (!"dev".equalsIgnoreCase(eurekaServerActive)){
			DingDingMessageUtil.sendTextMessage(eurekaServerActive+"环境-"+"【严重警告】："+event.getServerId() + "\t" + event.getAppName() + " 服务[下线]");
		}
		logger.error(event.getServerId() + "\t" + event.getAppName() + " 服务[下线]");
	}

	@EventListener
	public void listen(EurekaInstanceRegisteredEvent event) {
		InstanceInfo instanceInfo = event.getInstanceInfo();
		if (!"dev".equalsIgnoreCase(eurekaServerActive)){
			DingDingMessageUtil.sendTextMessage(eurekaServerActive+"环境-"+"【提示】："+instanceInfo.getAppName() + " 服务进行[注册]");
		}
		logger.info(instanceInfo.getAppName() + " 进行[注册]");
	}

	@EventListener
	public void listen(EurekaInstanceRenewedEvent event) {
		logger.info(event.getServerId() + "\t" + event.getAppName() + " 服务进行[续约]");
	}

	@EventListener
	public void listen(EurekaRegistryAvailableEvent event) {
		if (!"dev".equalsIgnoreCase(eurekaServerActive)){
			DingDingMessageUtil.sendTextMessage(eurekaServerActive+"环境-"+"【提示】："+"Eureka注册中心" + " 成功[启动]");
		}
		logger.info("Eureka注册中心启动[启动]");
	}

	@EventListener
	public void listen(EurekaServerStartedEvent event) {
		logger.info("Eureka Server 启动");
	}
}
